﻿using System;
using System.Collections.Generic;
using System.Text;
using Jayden.Dll.Web.Enums;

namespace Jayden.Dll.Web.Json
{
	public class JsonObject : Dictionary<string, JsonValue>, JsonValue
	{
		public void Add(string key, string value) { Add(key, new JsonString(value)); }
		public void Add(string key, bool value) { Add(key, new JsonBoolean(value)); }
		public void Add(string key, double value) { Add(key, new JsonNumber(value)); }
		public void Add(string key, byte value) { Add(key, new JsonNumber(value)); }
		public void Add(string key, Enum value) { Add(key, new JsonString(value.ToString())); }
		public void Add(string key, IEnumerable<string> value) { Add(key, new JsonArray(value)); }

		public void Replace(string key, JsonValue value) { base[key] = value; }

		public new JsonValue this[string key]
		{
			get
			{
				JsonValue value;
				if (!TryGetValue(key, out value))
					return null;
				return value;
			}
		}

		public string ToJson(RenderMode mode, int level)
		{
			StringBuilder builder = new StringBuilder();
			foreach (KeyValuePair<string, JsonValue> pair in this)
			{
				if (builder.Length > 0)
					builder.Append(',');
				if (mode == RenderMode.Debug)
				{
					builder.AppendLine();
					for (int c = 0; c < level; c++)
						builder.Append("\t");
				}
				builder.Append(JsonHelper.EncodeString(pair.Key));
				builder.Append(':');
				if(pair.Value == null)
					builder.Append(JsonHelper.Null);
				else
					builder.Append(pair.Value.ToJson(mode, level + 1));
			}
			if (mode == RenderMode.Debug && builder.Length > 0)
				builder.AppendLine();
			return "{" + builder.ToString() + "}";
		}
		public override string ToString() { return ToJson(RenderMode.Debug, 0); }
	}
}
